// 业务逻辑模块
// 包含各种可复用的业务功能

export class BusinessLogicManager {
    constructor() {
        this.isExecuted = false;
        this.executionTime = null;
        this.targetElements = [];
    }

    // 主要的业务逻辑执行函数
    execute(targetElements) {
        if (this.isExecuted) {
            console.log('业务逻辑已经执行过，跳过');
            return;
        }

        this.targetElements = targetElements;
        this.executionTime = new Date();

        console.log('开始执行业务逻辑...');
        console.log('执行时间:', this.executionTime);
        console.log('目标元素数量:', targetElements.length);

        try {
            // 执行各种业务逻辑
            this.extractData();
            this.processElements();
            this.sendNotifications();
            this.updateStorage();

            this.isExecuted = true;
            console.log('业务逻辑执行完成');

        } catch (error) {
            console.error('业务逻辑执行出错:', error);
        }
    }

    // 数据提取
    extractData() {
        console.log('开始提取数据...');

        const extractedData = [];

        this.targetElements.forEach((element, index) => {
            const data = {
                index: index,
                text: element.textContent?.trim() || '',
                className: element.className || '',
                attributes: this.getElementAttributes(element),
                timestamp: new Date().toISOString()
            };

            extractedData.push(data);
            console.log(`元素 ${index + 1} 数据:`, data);
        });

        // 存储提取的数据
        this.storeData('extractedData', extractedData);

        return extractedData;
    }

    // 处理元素
    processElements() {
        console.log('开始处理元素...');

        this.targetElements.forEach((element, index) => {
            // 示例：为元素添加标记
            element.setAttribute('data-processed', 'true');
            element.setAttribute('data-process-time', new Date().toISOString());

            // 示例：添加视觉反馈
            this.addVisualFeedback(element);

            console.log(`元素 ${index + 1} 处理完成`);
        });
    }

    // 发送通知
    sendNotifications() {
        console.log('发送通知...');

        // 向background script发送消息
        if (chrome && chrome.runtime) {
            chrome.runtime.sendMessage({
                type: 'xpathFound',
                data: {
                    elementCount: this.targetElements.length,
                    executionTime: this.executionTime,
                    url: window.location.href
                }
            }, function (response) {
                if (chrome.runtime.lastError) {
                    console.log('发送消息失败:', chrome.runtime.lastError);
                } else {
                    console.log('通知发送成功:', response);
                }
            });
        }

        // 页面内通知
        this.showPageNotification();
    }

    // 更新存储
    updateStorage() {
        console.log('更新存储...');

        const storageData = {
            lastExecution: this.executionTime.toISOString(),
            totalExecutions: this.getStoredData('totalExecutions', 0) + 1,
            targetUrl: window.location.href,
            elementCount: this.targetElements.length
        };

        this.storeData('executionHistory', storageData);
        this.storeData('totalExecutions', storageData.totalExecutions);
    }

    // 获取元素属性
    getElementAttributes(element) {
        const attributes = {};
        if (element.attributes) {
            for (let i = 0; i < element.attributes.length; i++) {
                const attr = element.attributes[i];
                attributes[attr.name] = attr.value;
            }
        }
        return attributes;
    }

    // 添加视觉反馈
    addVisualFeedback(element) {
        // 添加高亮效果
        element.style.border = '2px solid #00ff00';
        element.style.backgroundColor = 'rgba(0, 255, 0, 0.1)';

        // 3秒后移除高亮
        setTimeout(() => {
            element.style.border = '';
            element.style.backgroundColor = '';
        }, 3000);
    }

    // 显示页面通知
    showPageNotification() {
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #4CAF50;
            color: white;
            padding: 15px;
            border-radius: 5px;
            z-index: 10000;
            font-family: Arial, sans-serif;
            box-shadow: 0 4px 8px rgba(0,0,0,0.3);
        `;
        notification.textContent = `检测到目标元素，已处理 ${this.targetElements.length} 个元素`;

        document.body.appendChild(notification);

        // 5秒后自动移除
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 5000);
    }

    // 存储数据
    storeData(key, value) {
        try {
            if (chrome && chrome.storage) {
                chrome.storage.local.set({ [key]: value });
            } else {
                localStorage.setItem(key, JSON.stringify(value));
            }
        } catch (error) {
            console.error('存储数据失败:', error);
        }
    }

    // 获取存储的数据
    getStoredData(key, defaultValue = null) {
        try {
            if (chrome && chrome.storage) {
                // 异步获取，这里简化处理
                return defaultValue;
            } else {
                const data = localStorage.getItem(key);
                return data ? JSON.parse(data) : defaultValue;
            }
        } catch (error) {
            console.error('获取存储数据失败:', error);
            return defaultValue;
        }
    }

    // 重置执行状态
    reset() {
        this.isExecuted = false;
        this.executionTime = null;
        this.targetElements = [];
        console.log('业务逻辑状态已重置');
    }

    // 获取执行统计
    getStatistics() {
        return {
            isExecuted: this.isExecuted,
            executionTime: this.executionTime,
            elementCount: this.targetElements.length,
            totalExecutions: this.getStoredData('totalExecutions', 0)
        };
    }
}

// 创建全局实例
window.businessLogicManager = new BusinessLogicManager();

// 导出供其他模块使用
export default window.businessLogicManager; 